﻿function enableDeleteLink()
{
	$('a.deletelink').live("click", function () {
		if (confirm("Are you sure?")) {
			$(this).closest('form').submit();
		}
		return false;
	});
}

function enableListviewCommands() {
	$('.listview > li').find('a.cmd').hide();
	$('.listview > li').hover(function() {
		$(this).find('a.cmd').show();
	}, function() {
		$(this).find('a.cmd').hide();
	});
}

function displaySuccess(message) {
	displayMessage(message, "success");
}

function displayWarning(message) {
	displayMessage(message, "warning");
}

function displayError(message) {
	displayMessage(message, "error");
}

function displayMessage(message, messageType) {
	$("#messagewrapper").append('<div class="messagebox ' + messageType.toLowerCase() + '">' + message + '</div>');
	displayMessages("#messagewrapper");
}

function displayMessages(messageWrapperIdSelector) {
	if ($(messageWrapperIdSelector).children().length > 0) {
		$(messageWrapperIdSelector).show();
		$(document).click(function() {
			clearMessages(messageWrapperIdSelector);
		});
	} 
	else {
		$(messageWrapperIdSelector).hide();
	}
}

function clearMessages(messageWrapperIdSelector) {
	$(messageWrapperIdSelector).fadeOut(500, function () {
		$(messageWrapperIdSelector).empty();
	});
}

function enableAjaxIndicator(ajaxindicatorIdSelector) {
	$(document).ajaxStart(function () {
		$(ajaxindicatorIdSelector).show();
	}).ajaxStop(function () {
		$(ajaxindicatorIdSelector).hide();
	});
}

function handleAjaxMessages() {
	$(document).ajaxSuccess(function (event, request) {
		checkAndHandleMessageFromHeader(request);
	}).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
		checkAndHandleMessageFromHeader(jqXHR);
	});
}

function checkAndHandleMessageFromHeader(request) {
	var msg = request.getResponseHeader('X-Message');
	if (msg) {
		displayMessage(msg, request.getResponseHeader('X-Message-Type'));
	}
}

function enableCsrfAjaxProtection() {
	$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
		var verificationToken = $("meta[name='__AjaxRequestVerificationToken']").attr('content');
		if (verificationToken) {
			jqXHR.setRequestHeader("X-Request-Verification-Token", verificationToken);
		}
	});

}